"use client";
import { Suspense,useEffect, useState, useRef } from "react";
import { useParams } from "next/navigation";
import { VmsCopy } from "@/types/Model";
import { toast } from '@/hooks/use-toast'
import React from 'react';
import "reveal.js/dist/reveal.css";
import "reveal.js/plugin/highlight/zenburn.css";
import "reveal.js/dist/theme/white.css";
import dynamic from 'next/dynamic';
const LazyRevealPresentation = React.lazy(() => import('../ppt'));
import { RevealPresentationHandle } from '../ppt';
import { Button } from "@/components/ui/button";

export default function PPTGenerationPage() {
  const searchParams = useParams();
  const copy_id = searchParams.copy_id;
  const [copy, setCopy] = useState<VmsCopy | null>(null);
  const [loading, setLoading] = useState(true);
  const [pages, setPages] = useState<string[]>(['## 幻灯片1', '\n## 新幻灯片2\n']);
  const [pptContent, setPptContent] = useState<string>(pages.join('\n---\n'));
  const [currentSlide, setCurrentSlide] = useState(0);
  const [isGenerating, setIsGenerating] = useState(false); // 新增生成状态
  const revealRef = useRef<RevealPresentationHandle>(null);

  const jumpToSlide = (index: number) => {
    if (revealRef.current) {
      revealRef.current.goToSlide(index);
    }
  };
  
  const gradients = [
    'linear-gradient(to right, #4ade80, #3b82f6)' , // green-400 to blue-500
    'linear-gradient(to right, #f87171, #f59e0b)' , // red-400 to yellow-500
    'linear-gradient(to right, #fbbf24, #22d3ee)' , // amber-400 to cyan-500
    'linear-gradient(to right, #34d399, #fbbf24)' , // emerald-400 to amber-500
    'linear-gradient(to right, #8b5cf6, #fb7185)' , // violet-400 to rose-500
    'linear-gradient(to right, #a855f7, #ec4899)' , // purple-500 to pink-500
  ];

  useEffect(() => {
    // 随机选择一个渐变
    const randomGradient = gradients[Math.floor(Math.random() * gradients.length)];
  
    const style = document.createElement('style');
    style.innerHTML = `
      .reveal {
        background: ${randomGradient};
      }
      // .reveal h1 {
      //   color: #ff6f61;
      // }
    `;
    document.head.appendChild(style);
  
    return () => {
      document.head.removeChild(style);
    };
  }, [gradients]); // 添加 gradients 作为依赖项



  const fetchCopy = async () => {
    try {
      if (!copy_id) return;
      
       // 确保在客户端执行
       if (typeof window === 'undefined') return;
      
       const token = localStorage.getItem('token');
       if (!token) {
         throw new Error('No authentication token found');
       }
      
      const response = await fetch(`/api/copy/${copy_id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        throw new Error('Failed to fetch copy');
      }
      
      const data = await response.json();
      setCopy(data);
      if (data.ppt_content) {
        setPptContent(data.ppt_content);
        setPages(data.ppt_content.split('\n---\n'));
      } else {
        setPptContent('## 幻灯片1\n\n---\n## 新幻灯片2\n');
        setPages(['## 幻灯片1', '\n## 新幻灯片2\n']);
      }
      
      toast({
        title: '提示',
        description: 'F 键进入演示, ESC 键退出',
      })

    } catch (error) {
      console.error('Error fetching copy:', error);
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

    useEffect(() => {
        console.log(copy_id)
        if (copy_id) {
          fetchCopy();
        }
  }, [copy_id]);

  const generatePPT = async () => {
    try {
      if (!copy_id) {
        throw new Error('No copy ID provided');
      }

      const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
      if (!token) {
        throw new Error('No authentication token found');
      }

      setIsGenerating(true); // 开始生成时设置为true
      toast({
        title: 'PPT生成中',
        description: '正在生成PPT...',
      });

      const response = await fetch(`/api/copy/generate_ppt/${copy_id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        throw new Error('Failed to generate PPT');
      }

      const copy = await response.json();
      setCopy(copy)
      setPptContent(copy.ppt_content || '');
      setPages(copy.ppt_content.split('\n---\n') || []);

      toast({
        title: 'PPT生成成功',
        description: 'PPT已成功生成',
      });
    } catch (error) {
      console.error('Error generating PPT:', error);
      toast({
        title: 'PPT生成失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setIsGenerating(false); // 无论成功失败，最后都设置为false
    }
  };

  const savePPT = async () => {
    try {
      if (!copy_id) {
        throw new Error('No copy ID provided');
      }

      const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
      if (!token) {
        throw new Error('No authentication token found');
      }

      toast({
        title: 'PPT保存中',
        description: '正在保存PPT...',
      });

     
      const updatedCopy = { ...copy, ppt_content: pptContent };
      const response = await fetch(`/api/copy`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedCopy)
      });

      if (!response.ok) {
        throw new Error('Failed to save PPT');
      }

      toast({
        title: 'PPT保存成功',
        description: 'PPT已成功保存',
      });
    } catch (error) {
      console.error('Error saving PPT:', error);
      toast({
        title: 'PPT保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  const addPage = (index?: number) => {
    const newContent = `\n## 新幻灯片${index?index+2:pages.length+1}\n`;
    
    if (typeof index === 'number') {

      pages.splice(index + 1, 0, newContent);
      setCurrentSlide(index+1)
    } else {
      pages.push(newContent);
      setCurrentSlide(pages.length)

    }
    setPages(pages);
    let pptContent = pages.join("\n---\n")
    setPptContent(pptContent);
    // console.log(pages)
 
  };

  const deletePage = (index: number) => {
    if (pages.length <= 1) {
      toast({
        title: '无法删除',
        description: '至少需要保留一个幻灯片',
        variant: 'destructive'
      });
      return;
    }

    const newPages = pages.filter((_, i) => i !== index);
    setPages(newPages);
    setPptContent(newPages.join("\n---\n"));
    
    // Update current slide if needed
    if (currentSlide >= newPages.length) {
      setCurrentSlide(newPages.length - 1);
    }
   
};


  const updatePage = (index: number, content: string) => {
    const newPages = [...pages];
    newPages[index] = content;
    setPages(newPages);
    setPptContent(newPages.join("\n---\n"));
    setCurrentSlide(index)
  };




  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }

  if (!copy) {
    return <div className="flex justify-center items-center h-screen">未找到文案</div>;
  }

  return (
    <div className="flex flex-col md:flex-row max-h-screen w-full">
      <div className="flex-1 w-full md:w-4/5 bg-gray-100 p-6 overflow-hidden">
        <div className={`w-full h-full aspect-w-16 aspect-h-9 rounded-lg    bg-slate-200 `} >
        <Suspense fallback={<div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>}>
        <LazyRevealPresentation
          ref={revealRef}
          content={pptContent}
          onSlideChange={(index) => console.log('Current slide:', index)}
        />
      </Suspense>
        </div>
      </div>

      <div className="w-full md:w-1/5 bg-gray-100 border-t md:border-l border-gray-200 p-6 overflow-auto">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-medium text-gray-700 dark:text-gray-300">
            幻灯片
          </h2>
          <Button
            variant="outline"
            onClick={() => window.location.href = `/copy/${copy_id}`}
          >
            返回
          </Button>
          <button
            onClick={generatePPT}
            disabled={isGenerating}
            className={`py-1 px-4 border border-transparent shadow-sm text-base font-medium rounded-md text-white ${
              isGenerating ? 'bg-gray-400 cursor-not-allowed' : 'bg-red-500 hover:bg-red-600'
            } focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500`}
          >
            {isGenerating ? '生成中...' : '生成'}
          </button>
    
          <button
            onClick={savePPT}
            className="py-1 px-4 border border-transparent shadow-sm text-base font-medium rounded-md text-white bg-red-500 hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
          >
            保存
          </button>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-1 gap-4">
          {pages.map((page, index) => (
            <div key={index} className="bg-white rounded-lg shadow-lg cursor-pointer">
              <textarea
                className="w-full h-fit overflow-y-scroll overflow-x-hidden rounded-lg shadow-lg p-2 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-400"
                rows={8}
                onClick={() => jumpToSlide(index)}
                onFocus={() => jumpToSlide(index)}
                value={page}
                onChange={(e) => updatePage(index, e.target.value)}
              />
              <div className="p-2 text-center text-sm font-medium text-gray-700 dark:text-gray-300">
                <button className="w-1/2" onClick={() => deletePage(index)}>
                  删除
                </button>
                <button className="w-1/2" onClick={() => addPage(index)}>
                  新建
                </button>
              </div>
            </div>
          ))}
          <button
            onClick={() => addPage()}
            className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-base font-medium rounded-md text-white bg-red-500 hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
          >
            新幻灯片
          </button>
        </div>
      </div>
    </div>
  );
}
